package down.xiaoheihe.work.Controller;

import com.alibaba.fastjson2.JSONObject;
import down.xiaoheihe.work.Entity.AddressList;
import down.xiaoheihe.work.Entity.AddressListExample;
import down.xiaoheihe.work.Entity.User;
import down.xiaoheihe.work.Entity.UserExample;
import down.xiaoheihe.work.Mapper.*;
import down.xiaoheihe.work.Response.AddressResponse;
import down.xiaoheihe.work.utils.CurPool;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@MapperScan("down.xiaoheihe.work.Mapper")
@CrossOrigin
public class UsersController {
    @Autowired
    UserMapper tUserMapper;
    @Autowired
    AddressListMapper addressListMapper;
    @GetMapping("/me")
    public User 获取个人信息(){
        Subject subject = SecurityUtils.getSubject();
        Integer id = (Integer) subject.getPrincipal();
        User user1 = tUserMapper.selectByPrimaryKey(id);
        return user1;
    }
    @PutMapping("/me")
    public User 更新个人信息(@RequestBody User user){
        Subject subject = SecurityUtils.getSubject();
        Integer id = (Integer) subject.getPrincipal();
        user.setUid(id);
        tUserMapper.updateByPrimaryKeySelective(user);
        User user1 = tUserMapper.selectByPrimaryKey(id);
        return user1;
    }
    /**
     * 个人主页
     * @return  返回的是一个map
     */
    @GetMapping("/gerenzhuye")
    public Map<String,Object> 个人主页(HttpServletResponse response){
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            Integer id = (Integer) subject.getPrincipal();
            User user = tUserMapper.selectByPrimaryKey(id);
            String url = user.getImage();
            String name = user.getUsername();
            Map<String,Object> a = new HashMap<>();
            a.put("url",url);
            a.put("name", name);
            a.put("uid",user.getUid());
            a.put("balance",user.getBalance());
            return a;
        }
        response.setStatus(401,"未登录");
        return null;
    }
    /**
     * 在修改资料界面首先获取当前用户资料
     * @param response
     * @return
     */
    @GetMapping("/mysetting")
    public Map<String, Object> 获取个人资料(HttpServletResponse response){
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            Integer id = (Integer) subject.getPrincipal();
            User user = tUserMapper.selectByPrimaryKey(id);
            String url = user.getImage();
            String name = user.getUsername();
            int sex = user.getGender();
            String sexString = String.valueOf(sex);
            String message = user.getDescribes();
            Map<String,Object> data = new HashMap<>();
            Date date = user.getBirthday();
            data.put("date", date);
            data.put("url",url);
            data.put("name", name);
            data.put("sex", sexString);
            data.put("message", message);
            return data;
        }
        response.setStatus(401,"未登录");
        return null;
    }
    /**
     * 修改头像
     * @param image 用户的image地址
     * @param response 响应
     * @return 返回的是map  map中key是  “image”  value  是 一串url
     */
    @PostMapping("/xiugaitouxiang")
    public Map<String, String> 修改头像(@RequestParam String image, HttpServletResponse response){
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            Integer id = (Integer) subject.getPrincipal();
            User user =  new User();
            user.setImage(image);
            user.setUid(id);
            tUserMapper.updateByPrimaryKeySelective(user);
            Map<String, String> map = new HashMap<>();

            map.put("image", user.getImage());
            return map;
        }
        response.setStatus(401, "未登录");
        return null;
    }
    @PostMapping("/xiugaiziliao")
    public void 修改个人资料(@RequestParam String name, @RequestParam String sex, @RequestParam String message, @RequestParam String date, HttpServletResponse response) {
        Subject subject = SecurityUtils.getSubject();
        Integer id = (Integer) subject.getPrincipal();
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(name);
        List<User> users = tUserMapper.selectByExample(userExample);
        if (users.size() > 0) {
            if (!users.get(0).getUid().equals(id)) {
                try {
                    response.sendError(402, "该用户名已经存在");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        User user = tUserMapper.selectByPrimaryKey(id);
        user.setUid(id);
        user.setUsername(name);
        user.setDescribes(message);
        try {
            Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
            user.setBirthday(date1);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        user.setGender(Integer.valueOf(sex));
        tUserMapper.updateByPrimaryKeySelective(user);
    }
    @GetMapping("/addresslist")
    public List<AddressResponse> 获取地址列表 (){
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            Integer id = (Integer) subject.getPrincipal();
            AddressListExample addressListExample = new AddressListExample();
            addressListExample.createCriteria().andUserIdEqualTo(id);
            List<AddressList> list = addressListMapper.selectByExample(addressListExample);
            List<AddressResponse> responses = new ArrayList<>();
            for (AddressList addressList : list){
                AddressResponse addressResponse = new AddressResponse();
                addressResponse.setId(addressList.getId());
                addressResponse.setName(addressList.getConsignee());
                addressResponse.setTel(addressList.getTel());
                addressResponse.setAddress(addressList.getProvince()+addressList.getCity()+addressList.getCounty()+addressList.getAddressDetail());
                addressResponse.setDefault(addressList.getIsDefault());
                responses.add(addressResponse);
            }
            return responses;
        }
        return null;
    }
    @PostMapping("/tianjiadizhi")
    public void 添加修改地址(@RequestBody JSONObject json, HttpServletResponse res){
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            Integer userId = (Integer) subject.getPrincipal();
            if (json.getInteger("id") == 0){
                AddressList addressList = new AddressList();
                addressList.setUserId(userId);
                addressList.setConsignee(json.getString("name"));
                addressList.setTel(json.getString("tel"));
                addressList.setProvince(json.getString("province"));
                addressList.setCity(json.getString("city"));
                addressList.setCounty(json.getString("county"));
                addressList.setPostalCodel(json.getString("postalCode"));
                addressList.setAddressDetail(json.getString("addressDetail"));
                addressList.setIsDefault(json.getBoolean("isDefault"));
                addressListMapper.insert(addressList);
                res.setStatus(201);
            }else{
                AddressList addressList = addressListMapper.selectByPrimaryKey(json.getInteger("id"));
                addressList.setConsignee(json.getString("name"));
                addressList.setTel(json.getString("tel"));
                addressList.setProvince(json.getString("province"));
                addressList.setCity(json.getString("city"));
                addressList.setCounty(json.getString("county"));
                addressList.setPostalCodel(json.getString("postalCode"));
                addressList.setAddressDetail(json.getString("addressDetail"));
                addressList.setIsDefault(json.getBoolean("isDefault"));
                addressListMapper.updateByPrimaryKeySelective(addressList);
                res.setStatus(200);
            }
        }
    }
    @PostMapping("/xiugaimima")
    public void 修改密码(@RequestParam String oldPassword, @RequestParam String newPassword,@RequestParam String salt, HttpServletResponse res) {
        Subject subject = SecurityUtils.getSubject();
        Integer id = (Integer) subject.getPrincipal();
        User user = tUserMapper.selectByPrimaryKey(id);
        if (!oldPassword.equals(user.getPassword())) {
            try {
                res.sendError(405, "旧密码错误");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            user.setPassword(newPassword);
            user.setSalt(salt);
            tUserMapper.updateByPrimaryKeySelective(user);
        }
    }
}
